DataFrame Indexing
The index is a set of labels used for selection and alignment. It does not have to be a database primary key, but uniqueness and ordering affect many operations.
Core indexers
df.loc["order-42", ["status", "amount"]] # labels
df.iloc[0:10, [1, 3]] # positions
df.at["order-42", "status"] # one scalar by label
df.iat[0, 1] # one scalar by position
Label slices with .loc are generally inclusive at both endpoints when the
labels are present; positional slices with .iloc follow normal Python
half-open semantics.
Set and reset
indexed = df.set_index("order_id", verify_integrity=True)
plain = indexed.reset_index()
Use verify_integrity=True when uniqueness is required. Sort an index when later
operations depend on ordered slicing or time-series behavior.
MultiIndex
A MultiIndex represents multiple label levels on an axis. It is useful when
hierarchical selection, reshaping, or grouped output is central:
by_region = sales.set_index(["country", "city"]).sort_index()
toronto = by_region.loc[("Canada", "Toronto")]
canada = by_region.loc["Canada"]
Prefer ordinary columns when the hierarchy is temporary or when downstream
tools expect flat tables. reset_index returns levels to columns.
Alignment hazard
Assignments and arithmetic involving pandas objects align by label. If position is intended, make that conversion explicit and verify lengths. Silent alignment is one of pandas' strengths, but also one of its most common sources of unexpected missing values.